//
//  ViewController.m
//  scrollTest
//
//  Created by leetangsong_macbk on 16/5/19.
//  Copyright © 2016年 macbook. All rights reserved.


#import "LTSCalendarView.h"
#import "LTSCalendarDayView.h"
#import "LTSCalendarContentView.h"

#import "LTSCalendarEventSource.h"
#import "LTSCalendarMonthView.h"
#import "LTSCalendarWeekView.h"


#define kTopBarWithStatusHeight 64
#define CriticalHeight 30  //滚动的 临界高度
@interface LTSCalendarView ()<UITableViewDelegate>



@property (nonatomic,strong)LTSCalendarContentView *contentView;


// 手指触摸 开始滚动 tableView 的offectY
@property (nonatomic,assign)CGFloat dragStartOffectY;
// 手指离开 屏幕 tableView 的offectY
@property (nonatomic,assign)CGFloat dragEndOffectY;

@property(nonatomic,strong) UIView *headerDiviView;


@property (nonatomic,assign)NSInteger nextFlag;

@end

@implementation LTSCalendarView
- (void)setDelegate:(id<LTSCalendarEventSource,LTSCalendarViewDelegate,UITableViewDataSource,UITableViewDelegate>)delegate{
    self.calendar.eventSource = delegate;
    self.tableView.dataSource = delegate;
    self.tableView.delegate = delegate;
    _delegate = delegate;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initUI];
    }
    return self;
}


- (void)initUI{
    
    self.containerView = [UIView new];
    
    
    UIView *diviView = [[UIView alloc]initWithFrame:CGRectMake(0, WEEK_DAY_VIEW_HEIGHT+5+1, mainW, 1)];
    diviView.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
    [self addSubview:diviView];
    self.headerDiviView=diviView;
    
    self.containerView.frame = CGRectMake(0, CGRectGetMinY(diviView.frame)+8, self.frame.size.width, self.frame.size.height - WEEK_DAY_VIEW_HEIGHT);
    [self addSubview:self.containerView];
    self.backgroundColor = [UIColor whiteColor];
    self.containerView.backgroundColor = [UIColor whiteColor];
    
    
   
    
    //添加 日历事件 表
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 1, CGRectGetWidth(self.containerView.frame), CGRectGetHeight(self.containerView.frame))];
    [self.containerView addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
    self.tableView.delegate = self;
    
    
    
    
    LTSCalendarManager *calendar = [LTSCalendarManager new];
    self.calendar = calendar;
    
    
    
    
    //初始化weekDayView
    LTSCalendarWeekDayView *weekDayView = [LTSCalendarWeekDayView new];
    weekDayView.frame = CGRectMake(0, 0, self.frame.size.width, WEEK_DAY_VIEW_HEIGHT);
    weekDayView.backgroundColor=[UIColor whiteColor];
    self.calendar.weekDayView = weekDayView;
    
    LTSCalendarSelectedWeekView *weekView = [LTSCalendarSelectedWeekView new];
    
    weekView.pagingEnabled = YES;
    [calendar setSelectedWeekView:weekView];
    weekView.frame = CGRectMake(0, 400, self.frame.size.width, 50);
    
    
    //初始化  contentViw
    LTSCalendarContentView *contentView= [LTSCalendarContentView new];
    self.contentView = contentView;
    [calendar setContentView:contentView];
    
    
   
   
    
    UIView *headerView = [UIView new];
    
    headerView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:contentView];
    [headerView addSubview:weekView];
    
    self.headerView = headerView;
    
    self.tableView.tableHeaderView = headerView;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    
    UIView *toNextView = [[UIView alloc]initWithFrame:CGRectMake(mainW/2-80, 240-18, 160, 18)];
    toNextView.backgroundColor=[UIColor clearColor];
    
    [headerView addSubview:toNextView];
     [headerView insertSubview:toNextView atIndex:999];
    
    UIImageView *toNextImageView = [[UIImageView alloc]initWithFrame:CGRectMake(80-10,11, 24, 8)];
    toNextImageView.image=[UIImage imageNamed:@"menu_next"];
    [toNextView addSubview:toNextImageView];
    //    view.backgroundColor = [UIColor grayColor];
    
    [self.calendar.calendarAppearance addObserver:self forKeyPath:@"weekDayHeight" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
   
    //初始化外观
    [self configurOriginalAppearance];
    
    //数据加载完
//    [self.calendar reloadData];
    //初始化 第一项数据  初始数据
    self.calendar.currentDateSelected = [NSDate date];
    
    self.calendar.lastSelectedWeekOfMonth = [self.calendar getWeekFromDate:self.calendar.currentDateSelected];
    
    
    
    
    
    [self addSubview:weekDayView];
    [self bringSubviewToFront:weekDayView];
    
    self.calendar.currentDate = [NSDate date];
    
    [self.calendar reloadData];
    self.backgroundColor = self.calendar.calendarAppearance.backgroundColor;
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:toNextView andWithBlick:^(UIView *view) {
//        if (self.nextFlag==1) {
//             [self showSingleWeekView:YES];
//        } else {
//             [self showAllView:YES];
//        }
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(calendarViewNextClick:)]) {
            [self.delegate calendarViewNextClick:self];
        }
       
    }];
    
}

- (void)configurOriginalAppearance{
    
    
    self.calendar.calendarAppearance.weekDayTextColor = DarkText;
    self.calendar.calendarAppearance.weekDayFormat = LTSCalendarWeekDayFormatFull;
    //self.calendar.calendarAppearance.dayCircleColorSelected=RGBCOLOR(251, 52, 65);
    self.calendar.calendarAppearance.dayTextColor = DarkText;
    self.calendar.calendarAppearance.lunarDayTextColorOtherMonth = PrimaryText;
    self.calendar.calendarAppearance.lunarDayTextColor = PrimaryText;
    self.calendar.calendarAppearance.dayTextColorOtherMonth = PrimaryText;
    self.calendar.calendarAppearance.backgroundColor = [UIColor whiteColor];
    self.calendar.calendarAppearance.dayDotColor = PrimaryText;
    self.calendar.calendarAppearance.dayDotColorSelected = PrimaryText;
    self.calendar.calendarAppearance.isShowLunarCalender = NO;
    self.calendar.calendarAppearance.dayDotSize = 6;
    self.calendar.calendarAppearance.dayCircleSize = 30;
//    self.calendar.calendarAppearance.dayBorderColorToday = [UIColor clearColor];
    self.calendar.calendarAppearance.weekDayHeight = 40;
    
    [self.calendar reloadAppearance];
    
}

- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context

{
    self.contentView.frame = CGRectMake(0, 0, self.frame.size.width, self.calendar.calendarAppearance.weekDayHeight * WEEKS_TO_DISPLAY);
    self.headerView.frame = CGRectMake(0, 0, self.frame.size.width, self.calendar.calendarAppearance.weekDayHeight * WEEKS_TO_DISPLAY);
//   [self.calendar reloadAppearance];
    self.calendar.currentDateSelected = [NSDate date];
    
}



- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    //初始化插入  第一个WeekView
    [self.calendar sendSubviewToSelectedWeekViewWithIndex:self.calendar.currentSelectedWeekOfMonth];
    self.calendar.currentDate = self.calendar.currentDate;

}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =[UITableViewCell new];
    cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    
    return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.delegate && [self.delegate respondsToSelector:@selector(calendarView:didSelectedIndexPath:)]) {
        [self.delegate calendarView:self didSelectedIndexPath:indexPath];
    }
}



//当tableView 滚动完后  判断位置
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    CGFloat startSingleOriginY = self.calendar.calendarAppearance.weekDayHeight*5;
    
    self.dragEndOffectY  = scrollView.contentOffset.y;
    //0方向向上 0 方向向下
    
    //用于判断滑动方向
    CGFloat distance = self.dragStartOffectY - self.dragEndOffectY;
    
    
    if (self.tableView.contentOffset.y > CriticalHeight ) {
        if (self.tableView.contentOffset.y < startSingleOriginY) {
            if (self.tableView.contentOffset.y > startSingleOriginY-CriticalHeight) {
                [self showSingleWeekView:YES];
                return;
            }
            //向下滑动
            if (distance < 0) {
                [self showSingleWeekView:YES];
            }
            
            else [self showAllView:YES];
        }
        
        
    }
    else if (self.tableView.contentOffset.y > 0)
        [self showAllView:YES];
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
   
   
    CGFloat startSingleOriginY = self.calendar.calendarAppearance.weekDayHeight*5;
    
    self.dragEndOffectY  = scrollView.contentOffset.y;
    //0方向向上0 方向向下
    CGFloat distance = self.dragStartOffectY - self.dragEndOffectY;
    
    
    if (self.tableView.contentOffset.y>CriticalHeight ) {
        if (self.tableView.contentOffset.y<startSingleOriginY) {
            if (self.tableView.contentOffset.y>startSingleOriginY - CriticalHeight) {
                [self showSingleWeekView:YES];
                return;
            }
            if (distance<0) {
                [self showSingleWeekView:YES];
            }
            else [self showAllView:YES];
        }
        
        
    }
    else if (self.tableView.contentOffset.y > 0)
        [self showAllView:YES];

    
    
    
}

//当手指 触摸 滚动 就 设置 上一次选择的 跟当前选择的 周 的index 相等
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.dragStartOffectY  = scrollView.contentOffset.y;
    
   self.calendar.lastSelectedWeekOfMonth = self.calendar.currentSelectedWeekOfMonth;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
   
    
    CGFloat offectY = scrollView.contentOffset.y;
    
    CGRect contentFrame = self.calendar.contentView.frame;


   //  当 offectY 大于 滚动到要悬浮的位置
   if ( offectY>self.calendar.startFrontViewOriginY) {
       
       
       contentFrame.origin.y = -self.calendar.startFrontViewOriginY;
       
       self.calendar.contentView.frame = contentFrame;

       
       //把 selectedView 插入到 containerView 的最上面
       [self.containerView insertSubview:self.calendar.selectedWeekView atIndex:996];
        //[self.containerView insertSubview:self.headerDiviView atIndex:999];
       
        // 把tableView 里的 日历视图 插入到 表底部
       [self.containerView insertSubview:self.calendar.contentView atIndex:0];
       [self.calendar setWeekViewHidden:YES toIndex:self.calendar.currentSelectedWeekOfMonth-1];
       
   }else{
       self.containerView.backgroundColor = self.calendar.calendarAppearance.backgroundColor;
       contentFrame.origin.y = 0;
       self.calendar.contentView.frame = contentFrame;
       [self.calendar setWeekViewHidden:NO toIndex:self.calendar.currentSelectedWeekOfMonth-1];
       [self.headerView insertSubview:self.calendar.selectedWeekView atIndex:1];
       [self.headerView insertSubview:self.calendar.contentView atIndex:0];
       
   }

    
    
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
}
//回到全部显示初始位置
- (void)showAllView:(BOOL)animate{
     DLog(@"回到全部显示初始位置");
    self.nextFlag=2;
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:animate];
    
  
}
//滚回到 只显示 一周 的 位置
- (void)showSingleWeekView:(BOOL)animate{
    DLog(@"滚回到 只显示 一周 的 位置");
    if (self.nextFlag==0) {
        self.nextFlag=1;
        return;
    }
    [self.tableView setContentOffset:CGPointMake(0, self.calendar.calendarAppearance.weekDayHeight*5-8) animated:animate];
    
    
}

-(void)dealloc{
    [self removeObserver:self forKeyPath:@"weekDayHeight"];
}



@end
